#!/usr/bin/python
# -*- encoding: utf-8 -*-

"""
@File:      tc_libunistring_libunistring_func_001.py
@Time:      2024/02/22 14:20:00
@Author:    suomengjun
@Version:   1.0
@Contact:   smj01095381@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    suomengjun
"""

import os
from common.basetest import LocalTest


class Test(LocalTest):
    """
    See tc_libunistring_libunistring_func_001.yaml for details

    :avocado: tags=P2,noarch,local,fixed
    """
    PARAM_DIC = {"pkg_name": "gcc libunistring libunistring-devel"}

    def setUp(self):
        super().setUp(self.PARAM_DIC)
        code_p = os.path.dirname(os.path.abspath(__file__))
        code = r'''cat > test_unistring_u8_strlen.c << EOF
#include <stdio.h>
#include <unistr.h>
#include "CODE_P/verify_utf8.h"

int main(int argc, char *argv[]) {
    if (argc < 2) {
        printf("Error:At least one parameter is required,but there are no parameters.\n");
        return 1;
    }
    const char *utf8_string = argv[1];
    if (!isValidUtf8(utf8_string)) {
        printf("Error: The string is NOT valid UTF-8--->(%s)\n", utf8_string);
        return 1;
    }    
    size_t num_chars = u8_strlen((uint8_t *)utf8_string);
    if (num_chars) {
        printf("u8字符数量: %zu(%s)\n", num_chars, utf8_string);
        return 0;
    } else {
        printf("Error: Failed to get string length correctly--->(%s:%zu)", utf8_string, num_chars);
        return 1;
    }
}
EOF'''
        self.cmd(code)
        self.cmd(f"sed -i 's|CODE_P|{code_p}|g' test_unistring_u8_strlen.c")      
        self.cmd(f"gcc -o test_unistring_u8_strlen test_unistring_u8_strlen.c {code_p}/verify_utf8.c -lunistring")

    def test(self):
        self.cmd("./test_unistring_u8_strlen 龙蜥")
        self.cmd("./test_unistring_u8_strlen longxi")
        self.cmd("./test_unistring_u8_strlen 123")
        self.cmd("./test_unistring_u8_strlen 你好，龙蜥")

    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        for file in ['test_unistring_u8_strlen.c', 'test_unistring_u8_strlen']:
            if os.path.exists(file):
                self.cmd(f"rm -rf {file}", ignore_status=True)
